﻿
using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using System;
namespace Xc.Views.Core
{
    /// <summary>
    /// 应用程序启动
    /// </summary>
    /// <typeparam name="TAppSetting"></typeparam>
    /// <typeparam name="TApplicationDbContext"></typeparam>
    public abstract class ApplicationBooster<TAppSetting, TApplicationDbContext> : ApplicationBooster<TAppSetting>, IApplicationBooster<TAppSetting, TApplicationDbContext>
where TAppSetting : class,new() where TApplicationDbContext : DbContext
    {
        public ApplicationBooster(string applicationName, string applicationVersion) : base(applicationName, applicationVersion)
        {

        }

        /// <summary>
        /// 启抽象类
        /// </summary>
        public ApplicationBooster()
        {
           
        }

        /// <summary>
        /// 添加服务
        /// </summary>
        /// <param name="serviceDescriptors"></param>
        protected override void BeforeBuild(IServiceCollection serviceDescriptors)
        {
            serviceDescriptors.AddPooledDbContextFactory<TApplicationDbContext>(OnConfigureDb, 128);
            base.BeforeBuild(serviceDescriptors);
        }
        /// <summary>
        /// 配置数据库时调用
        /// </summary>
        /// <param name="dbContextOptionsBuilder"></param>
        protected virtual void OnConfigureDb(DbContextOptionsBuilder dbContextOptionsBuilder)
        {
            dbContextOptionsBuilder.UseSqlite(base.ConnectionString);
        }
        /// <summary>
        /// 构建完成后执行如下代码
        /// </summary>
        /// <param name="serviceProvider"></param>
        protected override void AfterBuild(IServiceProvider serviceProvider)
        {
            var context = serviceProvider.GetService<IDbContextFactory<TApplicationDbContext>>();
            context.CreateDbContext().Database.Migrate();
            base.AfterBuild(serviceProvider);
        }
        /// <summary>
        /// 创建数据库上下文
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public abstract TApplicationDbContext CreateDbContext(string[] args);
    }
}
